var Q = require('q'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    BaseFun = require('../../../Base/server/controllers/Function'),
    BaseEnum = require('../../../Base/server/controllers/Enum'),
    BarcodeEnum = require('../../../Barcode/server/controllers/Enum.server.controller'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    assemblyRelationController = require('../../../Barcode/server/controllers/AssemblyRelation.server.controller');

exports.getBarcodeDataByAssembly = function(req, res) {
    var assemblyBarcode = req.body.Parameter.Barcode;

    barcodeMasterController.findBarcodeMasterByBarcode(assemblyBarcode, function(err, barcodeMaster){
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        if (barcodeMaster == null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询镭射标失败';
            newErr.message = '未找到对应的镭射标！';
            res.json({
                Data: null,
                Error: newErr
            });
            return;
        }
        barcodeMasterController.findAssemblyBarcodeMaster(barcodeMaster._id, function(err, assemblyBarcodeMaster) {
            if (err) {
                res.json({
                    Data: null,
                    Error: err
                });
            } else {
                if (!assemblyBarcodeMaster || !assemblyBarcodeMaster.BarcodeMaster) {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '查询芯片失败';
                    newErr.message = '未找到对应的芯片！';
                    res.json({
                        Data: null,
                        Error: newErr
                    });
                    return;
                } 
                res.json({
                    Data: assemblyBarcodeMaster.BarcodeMaster,
                    Error: null
                });
            }
        });
    });
};

//芯片失效，取此芯片主档装配关系中最新的条码主档信息
exports.getNewBarcodeData = function (req, res) {
    var parameter = req.body.Parameter,
        initBarcodeMaster = parameter.initBarcodeMaster;
    //初始条码的芯片失效，去装配关系表找最近的装配条码    
    assemblyRelationController.findAllByBarcodeMasterAndAssemblyType(initBarcodeMaster, function (err, result) {
        // console.log("getBarcodeData-------------"+result);
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询装配条码失败';
                newErr.message = '未找到对应的装配条码！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                
                barcodeMasterController.findBarcodeMasterByBarcodeMaster(result[0].AssemblyBarcode, function(err,result){
                   if (err) {
                        res.json({
                            Data: null,
                            Error: err
                        });
                    } else {
                        if (result == null) {
                            var newErr = new Error();
                            newErr.leval = 9;
                            newErr.title = '查询条码失败';
                            newErr.message = '未找到对应的条码！';
                            res.json({
                                Data: null,
                                Error: newErr
                            });
                        } else {
                            res.json({
                                Data: result,
                                Error: null
                            });
                        }
                    }
                });
            }
        }
    });
};
//提交确认
//newBarcode新芯片
//BarcodeMasterData(当前显示的)最新的条码信息
//initBarcodeMaster初始Barcode(newBarcode和initBarcode进行绑定)方法
exports.submitBarcodeData = function (req, res) {
    var parameter = req.body.Parameter,
        BarcodeMasterData = parameter.BarcodeMasterData,
        newBarcode = parameter.newBarcode,
        userId = parameter.userId,
        initBarcodeMaster = parameter.initBarcodeMaster;
    //保存当前条码主档的id
    var BarcodeMasterDataId = BarcodeMasterData._id;
    //把条码数据存入新芯片    
    var newBarcodeData = BarcodeMasterData;
    delete newBarcodeData._id;
    newBarcodeData.Barcode = newBarcode;
    // newBarcodeData.IsAssembly = true;
    var transactions = [];//存事务
    //新增条码
    newBarcodeData._id = BaseFun.getObjectId();
    newBarcodeData.RowStatus = BaseEnum.RowStatus.Insert.Value;
    newBarcodeData.CreatedBy = userId;
    transactions.push({
        EntityName: 'BarcodeMaster',
        Records: [newBarcodeData]
    });
    //更新当前芯片主档信息状态为失效
    var updateBarcodeData = {
        RowStatus: BaseEnum.RowStatus.Modify.Value,
        CreatedBy: userId,
        _id: BarcodeMasterDataId,
        SysVersion: BarcodeMasterData.SysVersion,
        Status: BarcodeEnum.BarcodeStatus.Invalid.Value
    };
    transactions.push({
        EntityName: 'BarcodeMaster',
        Records: [updateBarcodeData]
    });
    //新芯片和初始芯片创建装配关系
    var dateNow = Date.now();
    var assemblyRecord = {
        BarcodeMaster:initBarcodeMaster,
        AssemblyBarcode:newBarcodeData._id,
        AssemblyType:2,
        CollectDateTime:dateNow,
        _id: BaseFun.getObjectId(),
        RowStatus: BaseEnum.RowStatus.Insert.Value,
        CreatedBy: userId
    }
    transactions.push({
        EntityName: 'AssemblyRelation',
        Records: [assemblyRecord]
    });
                            
    Q.nfcall(Transaction.BatchSaveByTran, transactions).then(function () {
        res.json({
            Data: true,
            Error: null
        });
    }).catch(function(err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
};




